require 'rubygems'
require 'sinatra'


require 'dm-core'
require 'dm-aggregates'
require 'dm-types'
require 'dm-datastore-adapter/datastore-adapter'

DataMapper.setup(:datastore,
                 :adapter => :datastore,
                 :database => 'sinatratest2')


class Post
  include DataMapper::Resource
  def self.default_repository_name; :datastore end

  property :id, Serial
  property :body, Text
  property :created_at, DateTime

  has n, :viewers

  before :save do
    self.created_at = Time.now
  end
end

class Viewer
  include DataMapper::Resource
  def self.default_repository_name; :datastore end

  property :id, Serial
  property :number, Text

  belongs_to :post
end

get '/post' do
  body = <<-HTML
  Hello Sinatra on JRuby World!!<br />
<form method="POST">
  <input type="text" name="post[body]" />
  <input type="submit" value="post" />
</form>
Posts:<br />
HTML
  Post.all(:order => [:created_at.desc]).each do |post|
    body += "<div>id:#{post.id} body:#{post.body} created_at:#{post.created_at}</div>"
    for viewer in post.viewers.all do
      body += "<div>viewer number:#{viewer.number.to_s}</div>"
    end
  end
  body
end

post '/post' do
  @post = Post.create(params['post'])
  @post.viewers.create(:number => '1')
  @post.viewers.create(:number => '2')
  @post.viewers.create(:number => '3')
  @post.viewers.create(:number => '4')
  redirect '/post'
end
